# 基本计算器： https://leetcode-cn.com/problems/basic-calculator/solution/

# 官方题解
class Solution:
    def calculate(self, s: str) -> int:
        # 该位数字的符号
        preSign = 1
        # 结果
        rst = 0
        # 当前数的绝对值
        num = 0
        # 字符串长度
        n = len(s)
        # 定义数据栈
        data = list()
        symbol = list()

        for i in range(n):
            if s[i].isdigit():
                num = num*10 + ord(s[i]) - ord("0")
            elif s[i] == '+':
                rst = rst + num * preSign
                num = 0
                preSign = 1
            elif s[i] == '-':
                rst = rst + num * preSign
                num = 0
                preSign = -1
            # 当结果为 (, 将前面的计算结果压入栈, 并计算当前后面的符号
            elif s[i] == '(':
                data.append(rst)
                symbol.append(preSign)
                # 重置默认值
                rst = 0
                preSign = 1
            # 如果为右括号，将括号内的计算结果 与 ( 前面的结果结合
            elif s[i] == ')':
                # 先计算出 rst, 因为  像(2 + 3)， 最后碰到 ), 并没与计算出 2 + 3的值
                rst = rst + preSign * num
                # 重新置零 num， preSign
                num = 0
                preSign = 1
                a = data.pop()
                pre = symbol.pop()
                rst = pre * rst + a
            

        return rst + num * preSign
            

r = "(1+(4+5+2)-3)+(6+8)"
r = "17 - 13 + (1 - (2 - 3) + 3) + 42"
# r = "7+(-5)"
# r = "-7+(-5)"
# r = "-78 - 51 + 2 - 3"
s = Solution()
rst = s.calculate(r)  
print(rst)

